﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;

namespace TheMovieDBV3
{
    public class TmdbMovie
    {
        private string API_KEY = "6b3254ee1455766f9901e9ec383670d8";

        private List<string> _genres;
        private List<string> _cast;
        private List<string> _directors;
        private List<string> _writers;
        private List<TmdbImage> _posters;
        private List<TmdbImage> _backdrop;

        public TmdbMovie(string Id)
        {
            _genres = new List<string>();
            _directors = new List<string>();
            _writers = new List<string>();
            _cast = new List<string>();
            _posters = new List<TmdbImage>();
            _backdrop = new List<TmdbImage>();

            WebClient c = new WebClient();
            c.Headers.Add("Accept: application/json");
            c.Encoding = Encoding.UTF8;

            string stringData = c.DownloadString(string.Format("http://api.themoviedb.org/3/movie/{0}?api_key={1}&append_to_response=casts,images", Id, API_KEY));
            JsonTextReader r = new JsonTextReader(new StringReader(stringData));
            JObject j = (JObject)new JsonSerializer().Deserialize(r);

            #region MainData
            Title = j["title"].ToString();
            OriginalTitle = j["original_title"].ToString();

            ReleaseDate = j["release_date"].ToString();
            MovieId = Id;
            Imdb_Id = j["imdb_id"].ToString();
            Tagline = j["tagline"].ToString();

            JToken TokenGenres = j["genres"];
            foreach (var v in TokenGenres)
                _genres.Add(v["name"].ToString());
            #endregion

            #region People
            JToken jCasts = j["casts"];
            foreach (var v in jCasts["cast"])
                _cast.Add(v["name"].ToString());

            foreach (var v in jCasts["crew"])
            {
                if (v["department"].ToString() == "Writing")
                    _writers.Add(v["name"].ToString());
                else if (v["department"].ToString() == "Directing")
                    _directors.Add(v["name"].ToString());
            }
            #endregion

            #region Images
            JToken jimg = j["images"];
            foreach (var v in jimg["backdrops"])
                _backdrop.Add(new TmdbImage(v["file_path"].ToString(),
                    TmdbImageType.Backdrop, v["vote_average"].ToString()));

            foreach (var v in jimg["posters"])
                _posters.Add(new TmdbImage(v["file_path"].ToString(),
                    TmdbImageType.Poster, v["vote_average"].ToString()));
            #endregion
        }

        public string Title { get; set; }
        public string OriginalTitle { get; set; }

        public string ReleaseDate { get; set; }
        public string ReleaseYear
        {
            get
            {
                if (!string.IsNullOrEmpty(ReleaseDate))
                    return ReleaseDate.Substring(0, 4);

                return "1000";
            }
        }
        public string MovieId { get; set; }
        public string Imdb_Id { get; set; }
        public string Tagline { get; set; }
        public List<string> Genres
        { get { return _genres; } }
        public List<string> Cast
        { get { return _cast; } }
        public List<string> Director
        { get { return _directors; } }
        public List<string> Writer
        { get { return _writers; } }

        public List<TmdbImage> Posters
        { get { return _posters; } }
        public List<TmdbImage> Backdrops
        { get { return _backdrop; } }
        public TmdbImage MainPoster
        {
            get
            {
                if (Posters.Count == 0)
                    return null;
                else
                    return Posters[0];
            }
        }
        public TmdbImage MainBackdrop
        {
            get
            {
                if (Backdrops.Count == 0)
                    return null;
                else
                    return Backdrops[0];
            }
        }

        public static List<TmdbMovie> SearchMovie(string query, string ApiKey)
        {
            List<TmdbMovie> list = new List<TmdbMovie>();

            WebClient c = new WebClient();
            c.Headers.Add("Accept: application/json");

            string stringData = c.DownloadString(string.Format("http://api.themoviedb.org/3/search/movie?api_key={1}&query={0}", query.Replace(" ", "+"), ApiKey));
            JsonTextReader r = new JsonTextReader(new StringReader(stringData));
            JObject j = (JObject)new JsonSerializer().Deserialize(r);
            JToken res = j["results"];

            foreach (var v in res)
                list.Add(new TmdbMovie(v["id"].ToString()));

            return list;
        }
    }
    public class TmdbImage
    {
        private string BaseUrl = "http://cf2.imgobject.com/t/p/";
        private string _partialPath;
        private TmdbImageType _type;
        private double _vote;

        public TmdbImage(string partialPath, TmdbImageType imgType, string strVote)
        {
            _partialPath = partialPath;
            _type = imgType;
            _vote = Convert.ToDouble(strVote);
        }

        public TmdbImageType TYPE
        { get { return _type; } }
        public double Vote
        { get { return _vote; } }

        public string ThumbPath
        {
            get
            {
                if (_type == TmdbImageType.Backdrop)
                    return BaseUrl + "w300" + _partialPath;
                else
                    return BaseUrl + "w154" + _partialPath;
            }
        }
        public string OriginalPath
        {
            get { return BaseUrl + "original" + _partialPath; }
        }
        public string Name
        { get { return _partialPath.Replace("/", ""); } }

    }
    public enum TmdbImageType
    {
        Poster,
        Backdrop,
    }
}
